package com.invengo.module_robot.ui.fragment.weiget;

import android.content.Context;
import android.graphics.Canvas;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.invengo.library_orionstar.ActionEvent;
import com.invengo.library_orionstar.RobotManager;
import com.invengo.library_orionstar.SpeechEvent;
import com.invengo.module_robot.R;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;

public class SpeechView extends LinearLayout {
    private ImageView imageView;
    private TextView textView;
    PublishSubject<String> objectPublishSubject = PublishSubject.create();
    private String content = "";
    RequestOptions options = new RequestOptions()
            .fitCenter()
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.ALL);

    public SpeechView(@NonNull Context context) {
        this(context, null);
    }

    public SpeechView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SpeechView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //将打气筒根据自定义控件的布局文件，创建的view 对象挂载到当前类上面，然后显示
        LayoutInflater.from(context).inflate(R.layout.speech_view, this, true);
        imageView = findViewById(R.id.speechUrl);
        textView = findViewById(R.id.speechContent);
        initSpeechMessager();
        initOpeartionMessager();
        changeGif();
        objectPublishSubject
                .subscribeOn(Schedulers.io())
                .debounce(400, TimeUnit.MILLISECONDS)
                .delay(delayTime, TimeUnit.MILLISECONDS)
                .switchMap((Function<String, ObservableSource<Long>>) query -> {
                    return Observable.just(1L);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(hideConsumer);
    }


    /**
     * 隐藏消费者
     */
    private Consumer<Long> hideConsumer = new Consumer<Long>() {
        @Override
        public void accept(Long o) throws Exception {
            textView.setText("");
            textView.setVisibility(GONE);
        }
    };

    /**
     * 延迟时间
     */
    private long delayTime = 5000;

    /**
     * 初始化语音消息器
     */
    private void initSpeechMessager() {
        Messenger.getDefault().register(this, "SPEECH_TO_PAGE", SpeechEvent.class, event -> {
            switch (event.getEvent()) {
                case SpeechEvent.SPEECH_START:
                    RobotManager.getInstance().refreshTip();
                    gifRes = R.drawable.speed_listing;
                    changeGif();
                    break;
                case SpeechEvent.SPEECH_END:
                    gifRes = R.drawable.speed_tts;
                    changeGif();
                    break;
                case SpeechEvent.SPEECH_PAR:
                    KLog.e("是否执行了这不操作。。。 " + event.getContent());
                    this.content = event.getContent();
                    setContent(content);
                    break;
                case SpeechEvent.SPEECH_START_SEARCH:
                    if (searchCommand!=null&& !TextUtils.isEmpty(content)) {
                        searchCommand.execute(content);
                    }
                    break;
                case SpeechEvent.SPEECH_ANSWER:
                    RobotManager.getInstance().playText(event.getContent());
                    setContent(event.getContent());
                    break;
            }
        });
    }

    /**
     * init opeartion messenger
     */
    private void initOpeartionMessager() {
        Messenger.getDefault().register(this, "OPEARTION_TO_PAGE", ActionEvent.class, event -> {
            if (actionCommand!=null) {
                KLog.e("好的"+event.getEvent(),"SPEECH_TO_PAGE");
                // TODO: 2024/4/9 记得打开
                Messenger.getDefault().send(SpeechEvent.answer("好的"+event.getEvent()));
                actionCommand.execute(event);
            }
        });
    }



    private int gifRes = R.drawable.speed_tts;

    /**
     * 更改gif
     */
    private void changeGif() {
        Observable.just(gifRes)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    Glide.with(getContext())
                            .asGif()
                            .load(integer)
                            .apply(options)
                            .into(imageView);
                    RobotManager.getInstance().stopTTS();
                });
    }

    /**
     * 设置答案值
     *
     * @param answerValue 答案值
     */
    public void setAnswerValue(String answerValue) {
        if (answerValue == null)
            return;
        setContent(answerValue);
        RobotManager.getInstance().playText(answerValue);
    }

    /**
     * 设置内容
     *
     * @param text 文本
     */
    public void setContent(String text) {
        Observable.just(text)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    textView.setVisibility(VISIBLE);
                    textView.setText(s);
                    objectPublishSubject.onNext(s);
                });
    }

    /**
     * 抽签时
     *
     * @param canvas 帆布
     */
    @Override
    protected void onDraw(Canvas canvas) {
        textView.setText(content);
        KLog.e("执行ondraw");
        super.onDraw(canvas);
    }

    private BindingCommand<String> searchCommand;

    /**
     * 设置搜索命令
     *
     * @param searchCommand search命令
     */
    public void setSearchCommand(BindingCommand<String> searchCommand) {
        this.searchCommand = searchCommand;
    }

    private BindingCommand<ActionEvent> actionCommand;

    /**
     * 设置操作命令
     *
     * @param actionCommand 动作命令
     */
    public void setActionCommand(BindingCommand<ActionEvent> actionCommand) {
        this.actionCommand = actionCommand;
    }

    /**
     * 取消寄存器
     */
    public void unRegister() {
        Messenger.getDefault().unregister(this);
    }
}
